<template>
  <div>
    <div class="list-content" v-show="imgList.length > 0" v-for="(img,index) in imgList">
      <el-image @click="bigImg(`${img}`)" class="list-img" :src="`${img}`" :preview-src-list="srcList">
      </el-image>
      <el-button icon="el-icon-delete" class="wrong_class" @click="handleDelete(index)" />
    </div>
    <div class="list-head" @click="handleImport()">+</div>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg, .png, .webp"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-error="handleUploadError"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <p>仅允许导入jpg、png、bmp格式的图片文件</p>
          <p>大小不超过 <b style="color: #f56c6c">1MB,建议尺寸350*350</b></p>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    product: {
      type: Object
    }
  },
  data() {
    return {
      sourceImgList: [],
      imgList: [],
      srcList:["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"],
      loading: true,
      subLoading: false,
      previews: {},
      resizeHandler: null,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/product/uploadListImg"
      }
    };
  },
  watch: {
    product: {
      immediate: true,
      handler: function() {
        if (this.product.listImg !== undefined && this.product.listImg === '') {
          this.imgList = [];
          this.sourceImgList = [];
        } else if (this.product.listImg !== undefined && this.product.listImg !== '') {
          this.imgList = [];
          this.sourceImgList = this.product.listImg.split(',');
          for(let i=0; i<this.sourceImgList.length;i++) {
            this.imgList.push(process.env.VUE_APP_BASE_API + this.sourceImgList[i]);
          }
        }
      }
    },
  },
  methods: {
    handleImport() {
      this.upload.title = "商品图片上传";
      this.upload.open = true;
    },
    handleDelete(index) {
      this.imgList.splice(index, 1);
      this.sourceImgList.splice(index, 1);
      const listImg = this.sourceImgList.join(',');
      this.$emit('saveFile', listImg);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.imgList.push(process.env.VUE_APP_BASE_API + response.imgUrl);
      this.sourceImgList.push(response.imgUrl);
      const listImg = this.sourceImgList.join(',');
      this.$emit('saveFile', listImg);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      //this.$emit('saveFile', response.imgUrl);
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "修改结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    bigImg(url) {
      this.srcList[0] = url;
    },
  }
};
</script>

<style scoped lang="scss">

.list-content {
  //display: inline-block;
  margin-left: 20px;
  float: left;
}
.list-head {
  width: 120px;
	height: 120px;
  float: left;
  position: relative;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  line-height: 120px;
  text-align: center;
  margin-left: 20px;
}

.list-img {
  width: 120px; 
  height: 120px; 
  margin-bottom:-4px;
}

.wrong_class {
  width: 5px; 
  height: 5px; 
  float:right;
  margin-left: -30px;
  border: 0;
  position: absolute;
  z-index:999;
}
</style>
